import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'package:situation/app/theme/gaps.dart';
import 'package:situation/shared/util/util_gps.dart';

class AreaMeasureTool extends StatefulWidget {
  final Color fillColor;
  final Color borderColor;
  final double borderWidth;
  final TextStyle areaStyle;

  final Function? onClose;

  const AreaMeasureTool({
    super.key,
    this.fillColor = Colors.blue,
    this.borderColor = Colors.blue,
    this.borderWidth = 2.0,
    this.areaStyle = const TextStyle(color: Colors.white, fontSize: 12),
    this.onClose,
  });

  static late final GlobalKey<_AreaMeasureToolState> stateKey =
      GlobalKey<_AreaMeasureToolState>();

  static void addPoint(LatLng point) => stateKey.currentState?._addPoint(point);

  @override
  State<AreaMeasureTool> createState() => _AreaMeasureToolState();
}

class _AreaMeasureToolState extends State<AreaMeasureTool> {
  final List<LatLng> _points = [];
  final Distance _distanceCalculator = const Distance();

  void _addPoint(LatLng point) {
    setState(() => _points.add(point));
  }

  void _undoPoint() {
    if (_points.isEmpty) return;
    setState(() => _points.removeLast());
  }

  void _clearAll() {
    setState(() => _points.clear());
    if (widget.onClose != null) {
      widget.onClose!();
    }
  }

  double _calculateArea() {
    if (_points.length < 3) return 0;
    return UtilGps.calculateArea(_points).toDouble();
  }

  LatLng _calculateCentroid() {
    if (_points.isEmpty) return LatLng(0, 0);
    double x = 0, y = 0;
    for (final p in _points) {
      x += p.latitude;
      y += p.longitude;
    }
    return LatLng(x / _points.length, y / _points.length);
  }

  String _formatArea(double squareMeters) {
    if (squareMeters >= 1e6) {
      return '${(squareMeters / 1e6).toStringAsFixed(2)}km²';
    }
    return '${squareMeters.toStringAsFixed(2)}m²';
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 绘制测量点
        MarkerLayer(
          markers: [
            for (final point in _points)
              Marker(
                width: 20,
                height: 20,
                point: point,
                child: GestureDetector(
                  onLongPress: () => _undoPoint(),
                  child: Icon(Icons.circle, size: 20, color: Colors.blue),
                ),
              ),
          ],
        ),

        // 新增：动态连接线（最后一个点与第一个点的连线）
        PolylineLayer(
          polylines: [
            if (_points.length >= 2)
              Polyline(
                points: [_points.last, _points.first],
                color: widget.borderColor.withAlpha(150),
                strokeWidth: widget.borderWidth,
              ),
          ],
        ),

        // 绘制多边形区域
        PolygonLayer(
          polygons: [
            if (_points.length >= 3)
              Polygon(
                points: _points,
                color: widget.fillColor.withAlpha(120),
                borderColor: widget.borderColor,
                borderStrokeWidth: widget.borderWidth,
              ),
          ],
        ),

        // 面积显示标签
        MarkerLayer(
          markers: [
            if (_points.length >= 3)
              Marker(
                width: 100,
                height: 40,
                point: _calculateCentroid(),
                child: Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.all(2),
                  decoration: BoxDecoration(
                    color: Colors.black.withAlpha(120),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    _formatArea(_calculateArea()),
                    style: widget.areaStyle,
                  ),
                ),
              ),
          ],
        ),

        // 控制面板（复用距离测量的样式）
        Positioned(
          right: 20,
          bottom: Get.height * 0.4,
          child: Container(
            padding:
                _points.isEmpty
                    ? const EdgeInsets.all(0)
                    : const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.black.withAlpha(80),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Column(
              children: [
                if (_points.isNotEmpty) ...[
                  _buildIconButton(
                    icon: Icons.undo,
                    color: Colors.orange,
                    onPressed: _undoPoint,
                  ),
                  Gaps.vGap8,
                  _buildIconButton(
                    icon: Icons.clear,
                    color: Colors.red,
                    onPressed: _clearAll,
                  ),
                ],
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 复用图标按钮组件
  Widget _buildIconButton({
    required IconData icon,
    required Color color,
    required VoidCallback onPressed,
  }) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        padding: const EdgeInsets.all(6),
        decoration: const BoxDecoration(
          color: Colors.white,
          shape: BoxShape.circle,
        ),
        child: Icon(icon, size: 20, color: color),
      ),
    );
  }
}
